// --- 雷达图绘制代码 (保持不变) ---
const canvas = document.getElementById('radarCanvas'), ctx = canvas.getContext('2d'), container = document.getElementById('canvas-container'), MAX_D = 35, DANGER = 20, WARNING = 25;
let distances = [90,200,0,200,0,0];
function resizeCanvas() { const size = container.clientWidth; canvas.width = size; canvas.height = size; }
function drawRadar() {
    const cx = canvas.width/2, cy = canvas.height/2, r = Math.min(canvas.width/2, canvas.height/2) * 0.85, pulse = Math.sin(Date.now()*0.005)*8;
    ctx.clearRect(0,0,canvas.width,canvas.height); ctx.beginPath(); ctx.arc(cx, cy, r*0.7, 0, Math.PI*2); ctx.strokeStyle = 'rgba(50, 50, 50, 0.3)'; ctx.lineWidth = 1; ctx.stroke(); ctx.beginPath(); ctx.arc(cx, cy, r*0.5, 0, Math.PI*2); ctx.stroke();
    const sensors = [{x:cx, y:cy - r*0.4, sa:-130, ea:-50},{x:cx + r*0.4, y:cy - r*0.2, sa:-60, ea:0},{x:cx + r*0.4, y:cy + r*0.2, sa:0, ea:60},{x:cx, y:cy + r*0.4, sa:50, ea:130},{x:cx - r*0.4, y:cy + r*0.2, sa:120, ea:180},{x:cx - r*0.4, y:cy - r*0.2, sa:180, ea:240}];
    ctx.strokeStyle = 'rgba(100, 100, 100, 0.2)'; ctx.lineWidth = 1; sensors.forEach(s => { ctx.beginPath(); ctx.moveTo(cx, cy); ctx.lineTo(s.x, s.y); ctx.stroke(); });
    sensors.forEach((s,i) => {
        const d = distances[i], normalizedDistance = Math.min(d / MAX_D, 1), minRadius = r * 0.25, maxRadius = r * 0.55, ar = minRadius + normalizedDistance * (maxRadius - minRadius);
        let red, green, blue, glowSize;
        if (d < DANGER) { const t = d / DANGER; red = 255; green = Math.round(t * 100); blue = 68; glowSize = 20 + pulse; }
        else if (d < WARNING) { const t = (d - DANGER) / (WARNING - DANGER); red = 255; green = Math.round(195 + t * (196 - 195)); blue = Math.round(68 - t * 68); glowSize = 18 + pulse + t * 7; }
        else { const t = Math.min((d - WARNING) / (MAX_D - WARNING), 1); red = Math.round(255 - t * 255); green = 196; blue = Math.round(t * 118); glowSize = 25 + pulse; }
        const clr = `rgb(${red}, ${green}, ${blue})`, thickness = r*0.08, sa = s.sa * Math.PI/180, ea = s.ea * Math.PI/180;
        ctx.beginPath(); ctx.arc(s.x, s.y, ar, sa, ea); ctx.arc(s.x, s.y, ar - thickness, ea, sa, true); ctx.closePath(); const gradient = ctx.createRadialGradient(s.x, s.y, ar-thickness, s.x, s.y, ar); gradient.addColorStop(0, 'rgba(0,0,0,0)'); gradient.addColorStop(0.7, clr); gradient.addColorStop(1, clr); ctx.fillStyle = gradient; ctx.shadowColor = clr; ctx.shadowBlur = glowSize; ctx.fill(); ctx.shadowBlur = 0;
    });
    requestAnimationFrame(drawRadar);
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas(); drawRadar();

// --- UI 交互逻辑 ---
let isSearching = false, parkingInProgress = false, lastImage = null;
const findBtn = document.getElementById('find-spot-btn');
const spot1 = document.getElementById('spot-1');
const speedEl = document.getElementById('speed');
const cameraFeed = document.getElementById('camera-feed');
const cameraPlaceholder = document.querySelector('.camera-placeholder');

// 新增：参数和键盘输入逻辑
const secretCodeDisplay = document.getElementById('secret-code-display');
let codeDigits = ['0', '0'];
let isReplacingFirstDigit = true;

document.addEventListener('keydown', (event) => {
    if (/^[0-9]$/.test(event.key)) {
        const newDigit = event.key;
        if (isReplacingFirstDigit) { codeDigits[0] = newDigit; } 
        else { codeDigits[1] = newDigit; }
        isReplacingFirstDigit = !isReplacingFirstDigit;
        secretCodeDisplay.textContent = codeDigits.join('');
    }
});

function showPlaceholder(text, fontSize = '18px') {
    cameraPlaceholder.style.display = 'block';
    cameraPlaceholder.innerHTML = text;
    cameraPlaceholder.style.fontSize = fontSize;
    cameraFeed.style.display = 'none';
}
function showImage(src) {
    cameraFeed.src = src;
    cameraFeed.style.display = 'block';
    cameraPlaceholder.style.display = 'none';
}

// '寻找车位' 按钮的点击事件
findBtn.addEventListener('click', () => {
    if (parkingInProgress) return;
    isSearching = !isSearching;
    findBtn.textContent = isSearching ? '停止寻找' : '寻找车位';
    findBtn.classList.toggle('searching', isSearching);
    if (isSearching) {
        showPlaceholder('寻找车位中<span class="spinner"></span>', '20px');
    } else {
        showPlaceholder('摄像头关闭');
        lastImage = null;
    }
    fetch('http://192.168.1.199/?action=' + (isSearching ? 'start_search' : 'stop_search'))
        .catch(e => console.error("无法连接到硬件设备以控制搜索:", e));
});

// '车位1' 按钮的点击事件
spot1.addEventListener('click', () => {
    if (spot1.classList.contains('disabled') || parkingInProgress) return;

    parkingInProgress = true;
    spot1.classList.add('active');
    const code = codeDigits.join('');
    showPlaceholder(`指令已发送 (参数: ${code})<br>正在泊入车位...<span class="spinner"></span>`, '20px');
    
    const url = `http://127.0.0.1:5000/run_script?params=${code}`;
    
    console.log(`正在向本地服务器发送请求: ${url}`);
    
    fetch(url)
        .then(response => {
            if (!response.ok) {
                return response.json().then(err => { throw new Error(err.message || `服务器返回错误: ${response.status}`) });
            }
            return response.json();
        })
        .then(data => {
            console.log('来自本地服务器的响应:', data);
            if (data.status !== 'success') {
                showPlaceholder(`启动失败: ${data.message}`);
                alert(`启动脚本失败: ${data.message}`);
                parkingInProgress = false; // 启动失败，允许重试
                spot1.classList.remove('active');
            }
        })
        .catch(error => {
            console.error('Fetch Error:', error);
            const errorMessage = '连接本地服务器失败！<br>请确保 server.py 正在运行。';
            showPlaceholder(errorMessage);
            alert(errorMessage.replace(/<br>/g, '\n'));
            parkingInProgress = false; // 连接失败，允许重试
            spot1.classList.remove('active');
        });
});

// 与硬件的数据轮询
setInterval(async () => {
    try {
        const res = await fetch('http://192.168.1.199/');
        const data = await res.json();

        // 与硬件状态同步
        isSearching = data.search === 1;
        distances = data.distances || distances;
        speedEl.textContent = data.speed.toFixed(2);
        
        if (data.image) {
            lastImage = 'data:image/jpeg;base64,' + data.image;
        }

        // 根据状态决定UI显示
        if (parkingInProgress) {
            // 在泊车过程中，保持 "正在泊入" 的显示
            if (data.parking_status === 'finished' || data.parking_status === 'idle') {
                parkingInProgress = false;
                spot1.classList.remove('active');
            }
        } else {
            // 当不处于泊车流程中时，UI完全由硬件数据决定
            findBtn.textContent = isSearching ? '停止寻找' : '寻找车位';
            findBtn.classList.toggle('searching', isSearching);
            spot1.classList.toggle('disabled', data.found !== 1);
            
            if (!isSearching && lastImage) {
                showImage(lastImage);
            } else if (isSearching) {
                showPlaceholder('寻找车位中<span class="spinner"></span>', '20px');
            } else {
                showPlaceholder('摄像头关闭');
            }
        }
    } catch (e) {
        console.error('硬件数据轮询错误:', e);
    }
}, 200);